<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="550px"
    @close="close"
  >
    <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="品牌名称" prop="brandName" required>
        <el-input
          v-model="form.brandName"
          placeholder="请输入品牌名称"
          :disabled="isdetail"
        />
      </el-form-item>
      <el-form-item label="上传Logo">
        <div v-if="isdetail">
          <el-image
            style="width: 100px; height: 100px"
            :src="form.brandLogo"
            :fit="cover"
          />
        </div>
        <div v-else>
          <el-upload
            :action="action"
            list-type="picture-card"
            :headers="headers"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :show-file-list="false"
            limit="1"
          >
            <el-icon v-if="!form.brandLogo">
              <Plus />
            </el-icon>
            <img
              v-if="form.brandLogo"
              :src="form.brandLogo"
              alt=""
              style="width: 148px; height: 148px"
            />
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="form.brandLogo" alt="Preview Image" />
          </el-dialog>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { baseURL } from '@/config'
  import { addBrand, updateBrand } from '@/api/brand'
  import { fetchDeptList } from '@/api/departmentManagement'
  import { defineProps } from 'vue'
  import { useUserStore } from '@/store/modules/user'
  import { computed } from 'vue'

  export default defineComponent({
    name: 'AssetManagementAddEdit',
    emits: ['fetch-data'],
    setup(prop, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const userStore = useUserStore()
      const { token } = storeToRefs(userStore)
      const state = reactive({
        formRef: null,
        headers: {},
        treeData: [],
        action: '',
        num: 1,
        defaultProps: {
          children: 'children',
          label: 'title',
        },
        form: {},
        rules: {
          brandName: [
            { required: true, trigger: 'blur', message: '请输入品牌名称' },
          ],
        },
        assetCategoryData: [],
        deptListData: [],
        dialogFormVisible: false,
        title: '',
      })
      const dialogImageUrl = ref('')
      const dialogVisible = ref(false)
      const props = defineProps({
        assetCategoryData: Array,
        deptListData: Array,
      })
      const isdetail = computed(() => state.title === '详情')
      const handleRemove = (uploadFile, uploadFiles) => {
        console.log(uploadFiles.response)
      }
      const handleSuccess = (uploadFile) => {
        state.form.brandLogo = uploadFile.data.url
      }
      const handlePictureCardPreview = (uploadFile) => {
        dialogImageUrl.value = uploadFile.url
        dialogVisible.value = true
      }
      const handledepartmentChange = (value) => {
        state.form.deptId = value[value.length - 1]
      }
      const handleClassifyChange = (value) => {
        state.form.cateId = value[value.length - 1]
      }
      const showEdit = (row, type) => {
        state.form = {}
        if (!row) {
          state.title = '添加'
          // state.form.count = 1
        } else {
          state.title = type === 'detail' ? '详情' : '编辑'
          if (row.id) {
            state.form.count = row.id
          }
          const tempForm = JSON.parse(JSON.stringify(row))
          const imgArr = []
          if (tempForm.brandLogo) {
            imgArr.push(tempForm.brandLogo)
            tempForm.brandLogo = imgArr
          }
          // if (
          //   tempForm.deptTreePath.length === 1 &&
          //   tempForm.deptTreePath === '0'
          // ) {
          //   tempForm.deptId = [ 0, 1]
          // } else {
          tempForm.deptTreePath &&
            (tempForm.deptId = transitionFunc(
              tempForm.deptTreePath,
              tempForm.deptId,
              1
            ).map(Number))
          // }
          tempForm.cateTreePath &&
            (tempForm.cateId = transitionFunc(
              tempForm.cateTreePath,
              tempForm.cateId,
              2
            ).map(Number))

          state.form = tempForm
        }
        state.dialogFormVisible = true
      }

      const transitionFunc = (path, id) => {
        const newArr = path.split(',')
        // if (type == 1) {
        if (path.length > 1) {
          newArr.shift()
        }
        // }
        newArr.push(id)
        return newArr
      }

      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            if (state.title === '编辑') {
              if (Array.isArray(state.form.brandLogo)) {
                state.form.brandLogo = state.form.brandLogo[0]
              }
            }
            try {
              const { msg } =
                state.title === '添加'
                  ? await addBrand(state.form)
                  : await updateBrand(state.form)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              emit('fetch-data')
              close()
            } catch (err) {
              console.error(err)
            }
          }
        })
      }

      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.dialogFormVisible = false
      }

      const fetchdeptListDataData = async () => {
        try {
          const { data: data } = await fetchDeptList()
          state.deptListData = data
        } catch (e) {
          console.error(e)
        }
      }
      fetchdeptListDataData()
      onMounted(() => {
        const tokens = JSON.parse(JSON.stringify(token))
        state.headers['Authorization'] = `Bearer ${tokens._object.token}`
        state.action = `${baseURL}/zgyp-system/api/v1/files`
      })
      return {
        ...toRefs(state),
        showEdit,
        save,
        close,
        handledepartmentChange,
        handlePictureCardPreview,
        handleRemove,
        handleClassifyChange,
        handleSuccess,
        props,
        isdetail,
      }
    },
  })
</script>
<style scoped>
  .tree-container {
    width: 100%;
    min-height: 200px;
    border: 1px solid #dcdfe6;
  }
</style>
